<template>
  <div class="app-container">
    <ai_nabar style="margin: 10px 0 10px 0px;" index="2"></ai_nabar>
    <!-- 搜索栏部分 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关键词" prop="keywords">
        <el-input v-model="queryParams.keywords" @keyup.enter.native="handleQuery" placeholder="请输入关键词" clearable />
      </el-form-item>

      <el-form-item label="设置时间" prop="createTime">
        <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 添加按钮部分 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['arbit:wcremindmonitor:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['arbit:wcremindmonitor:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['arbit:wcremindmonitor:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 信息栏部分 -->
    <el-table v-loading="loading" :data="wcRemindMonitorList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" align="center" :show-overflow-tooltip="true" />

      <el-table-column label="关键词" prop="keywords" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="设置时间" prop="createTime" align="center" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" prop="remark" align="center" :show-overflow-tooltip="true"/> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['arbit:wcremindmonitor:edit']">修改</el-button>

          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['arbit:wcremindmonitor:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改提醒词监控对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div class="dia-box">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <span style="font-size: 14px;margin-right: 10px;color: #333;">新建标签</span>
          <!-- <el-input v-model="inputText" placeholder="请输入关键词" /> -->
          <div style="width: 280px;margin: 10px 0 50px 0;">
            <el-input placeholder="请输入标签名" v-model="inputText" class="input-with-select">
              <el-button slot="append" @click="addKeyword">保存</el-button>
            </el-input>
          </div>
          <!-- <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addKeyword">添加关键词</el-button> -->
          <div style="margin-top: 20px;" class="dia-box-lable">
            <span style="font-size: 14px;color: #9aa5aa;">已添加：</span>
            <el-tag v-for="(keyword, index) in whole" :key="index" closable @close="handleTagClose(keyword)">
              {{ keyword }}
            </el-tag>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 修改对话框 -->
    <el-dialog :title="title" :visible.sync="openchange" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="form.keywords" placeholder="请输入关键词" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ai_nabar from '../components/ai_nabar.vue'
import request from '@/utils/request';
import * as XLSX from 'xlsx';
export default {
  components: {
    ai_nabar
  },
  name: "WcRemindMonitor",
  data() {
    return {

      selection: [],
      inputText: '',
      whole: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 提醒词监控表格数据
      wcRemindMonitorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openchange: false,
      chatTime: [],  //时间器储存
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        keywords: [
          { required: true, message: "关键词不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理标签关闭事件
    handleTagClose(keyword) {
      this.whole = this.whole.filter(item => item !== keyword);
    },

    addKeyword() {
      if (this.inputText.trim() !== "") {
        this.whole.push(this.inputText.trim());
        this.inputText = ""; // 清空输入框
      }
      
    },
    /** 查询提醒词监控列表 */
    getList() {
      this.loading = true;
      listWcRemindMonitor(this.queryParams).then(res => {
        if (res['success']) {
          const dt = res['data'];
          this.total = dt['total'];
          this.wcRemindMonitorList = dt['records'];
        }
        this.loading = false;
      });
      setTimeout(()=>{
        this.loading = false;
      },2000)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openchange = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        keywords: null,

        remark: null,
        createBy: null,

        updateBy: null,
        updateTime: null,
        delFlag: null,


        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
      if (this.chatTime != '' && this.chatTime != null) {
        this.queryParams.beginTime = this.chatTime[0]+' 00:00:00'
        this.queryParams.endTime = this.chatTime[1]+' 23:59:59'
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime=[]
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // this.openchange = true;
      // this.openAddDialog = true;
      this.title = "添加提醒词监控";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWcRemindMonitor(id).then(response => {
        this.form = response.data;
        // this.open = true;
        this.openchange = true;
        // this.openEditDialog = true;
        this.title = "修改提醒词监控";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 这是修改的逻辑   修改中必须含有id
            updateWcRemindMonitor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openchange = false;
              this.getList();
            });
          } else {
            const data = this.whole.map(keyword => {
              return { keywords: keyword };
            });

            // 调用批量添加接口
            addList(data).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.openchange = false;
              this.reset(); // 重置表单
              this.getList(); // 重新获取列表

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除提醒词监控编号为"' + ids + '"的数据项？').then(function () {
        return delWcRemindMonitor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('wxassistant/wcremind_monitor/export', {
    //     ...this.queryParams
    //   }, `wcRemindMonitor_${new Date().getTime()}.xlsx`)
    // }
    handleExport() {
      if (this.ids.length > 0) {
        this.exportExcel()
      } else {

        this.$message.warning('请选择要导出的数据！');
      }
    },
    exportExcel() {
      // 假设你有一个表格数据的数组
      const data = [["关键词", "设置时间"],]; // 根据您的需求，这里应该是您想要导出的列标题

      // 遍历this.ids，找到对应的记录，并添加到data中
      this.ids.forEach(id => {
        // 假设this.wcRemindMonitorList是包含所有数据的一个数组
        const record = this.wcRemindMonitorList.find(item => item.id === id);
        if (record) {
          // 添加记录到data数组中，根据您的需求，这里应该是记录的对应字段
          data.push([record.keywords, record.createTime]);
        }
      });

      // 如果没有选中任何记录，则返回
      if (data.length === 1) {
        this.$message.warning('请选择要导出的数据！');
        return;
      }

      // 将数据转换为工作表
      const ws = XLSX.utils.aoa_to_sheet(data);

      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }

      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `selected_wcRemindMonitor_${new Date().getTime()}.xlsx`);
    }
  }
};

/** js请求 调用 */

// 查询提醒词监控列表
export function listWcRemindMonitor(query) {
  return request({
    url: '/wxassistant/wcremind_monitor/page',
    method: 'get',
    params: query
  })
}

// 查询提醒词监控详细
export function getWcRemindMonitor(id) {
  return request({
    url: '/wxassistant/wcremind_monitor/queryById/' + id,
    method: 'get'
  })
}

// 新增提醒词监控
export function addWcRemindMonitor(data) {
  return request({
    url: '/wxassistant/wcremind_monitor/add',
    method: 'post',
    data: data
  })
}

// 修改提醒词监控
export function updateWcRemindMonitor(data) {
  return request({
    url: '/wxassistant/wcremind_monitor/edit',
    method: 'put',
    data: data
  })
}

// 删除提醒词监控
export function delWcRemindMonitor(id) {
  return request({
    url: '/wxassistant/wcremind_monitor/delete/' + id,
    method: 'delete'
  })
}

// 批量添加
export function addList(data) {
  return request({
    url: '/wxassistant/wcremind_monitor/addList',
    method: 'post',
    data: data
  })
}
</script>

<style scoped lang="scss">
.dia-box {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.dia-box-lable {
  width: 90%;
  border-radius: 5px;
  border: 1px solid #eee;
  min-height: 100px;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  margin-bottom: 20px;

  .lable-box {
    padding: 0 5px;
    height: 20px;
    line-height: 20px;
    margin-right: 10px;
    border: 1px solid #dcdcdc;
    background-color: #ebf4ff;
    font-size: 12px;
    border-radius: 3px;
  }

  .select {
    color: #fff;
    background-color: #4095e5;
  }
}
</style>
